<?php

namespace catchAdmin\apipatient\controller;

use catcher\exceptions\FailedException;
use think\Request;
use app\common\lib\Redis;
use catcher\CatchResponse;
use catcher\base\CatchController;
use app\common\model\ShoppingClassify as ClassifyModel;
use app\common\model\ShoppingSpu as SpuModel;
use app\common\model\ShoppingSku as SkuModel;

class Shopping extends CatchController
{
    /**
     * 分类列表
     * @return \think\response\Json
     */
    public function getClassify(): \think\response\Json
    {
        $isExists = Redis::getInstance()->redis->exists('shoppingClassify');

        if ($isExists) {
            $jsonData = Redis::getInstance()->redis->get('shoppingClassify');
            $list = json_decode($jsonData, true);
        }else{
            $list = (new ClassifyModel())->getList();
            if (!empty($list)) {
                $treeData = (new ClassifyModel())->order('sort', 'desc')->select()->toTree();
                $treeDataJson = json_encode($treeData, JSON_UNESCAPED_UNICODE);
                Redis::getInstance()->redis->set('shoppingClassify', $treeDataJson);
            }
        }
        return CatchResponse::success($list);
    }

    /**
     * 产品列表
     * @return \think\response\Json
     */
    public function getHzdShoppingProduct(): \think\response\Json
    {
        $list = (new SpuModel())->getList();
        foreach ($list as $key => $val) {
            $sku = (new SkuModel())->where('spu_id', $val['id'])->field('id,price')->order('price', 'asc')->find();
            if (!empty($sku['price'])) {
                $list[$key]['price'] = $sku['price'];
                $list[$key]['sku_id'] = $sku['id'];
            }
        }
        return CatchResponse::paginate($list);
    }

    /**
     * 商品详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function getHzdShoppingGoods(Request $request): \think\response\Json
    {
        $req = $request->post();
        $where = [];
        if (empty($req['spu_id'])) {
            throw new FailedException("产品id不能为空");
        }
        $where[] = ['spu_id', '=', $req['spu_id']];
        $list = (new SkuModel())->where($where)->select();
        return CatchResponse::success($list);
    }
}